package com.fintech.pangu.web.config;

import com.fintech.pangu.commons.jwt.JWTUtil;
import com.fintech.pangu.commons.model.UserDetail;
import com.fintech.pangu.keyvault.KeyVaultObtain;
import com.fintech.pangu.web.util.UserInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 */
@Slf4j
public class UserInfoJWTHeaderInterceptor extends PanGuHandlerInterceptor {
    private static final String DEFAULT_JWT_TOKEN_NAME = "xToken";

    @Autowired
    private KeyVaultObtain keyVaultObtain;

    @Override
    public int interceptorOrder() {
        return 0;
    }

    @Override
    public String pathPatterns() {
        return "/**";
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String xToken = request.getHeader(DEFAULT_JWT_TOKEN_NAME);
        if(StringUtils.isNotBlank(xToken)) {
            UserDetail userDetail = JWTUtil.getUserInfoFromJWT(xToken,keyVaultObtain.getKey());
            if (log.isDebugEnabled() && userDetail != null){
                log.debug("UserInfoDetails:[{}]",userDetail.toString());
            }
            UserInfoUtils.set(userDetail);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoUtils.remove();
    }
}
